package com.example.tiptravel.api;

import com.example.tiptravel.constast.AppConstast;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by 45820 on 2016/11/5.
 */

public class RetroManager {
    private static volatile RetroManager instance = null;

    private Retrofit retrofit;
    private Gson gson;
    private OkHttpClient client;
    private static final int DEFAULT_READ_TIMEOUT = 15 * 1000;
    private static final int DEFAULT_CONNECT_TIMEOUT = 15 * 1000;
    private static final int DEFAULT_WRITE_TIMEOUT = 15 * 1000;


    private RetroManager() {
        initGson();
        initOkhttpClient();
        initRetrofit();
    }

    public static RetroManager getInstance() {
        if (instance == null) {
            synchronized (RetroManager.class) {
                if (instance == null) {
                    instance = new RetroManager();
                }
            }
        }
        return instance;
    }

    private void initRetrofit() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(AppConstast.BASE_URL)
                    .client(client)
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
    }

    private void initOkhttpClient() {
        if (client == null) {
            client = new OkHttpClient.Builder()
                    .readTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.MILLISECONDS)
                    .connectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                    .writeTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
                    .build();
        }
    }

    private void initGson() {
        gson = new GsonBuilder()
                .serializeNulls()
                .create();
    }

    public HomeService getHomeService(){
        return retrofit.create(HomeService.class);
    }

    public PostService getPostService(){
        return  retrofit.create(PostService.class);
    }
}
